#!/usr/bin/python
#coding=utf-8
import inspect,os,sys,mimetypes,re
from email.mime.text import MIMEText
from smtplib import SMTP as smtp
import ConfigParser
class mail(object):
    def __init__(self,from_='',sub_='',content_=''):
        self.from_=from_
        self.sub_=sub_
        self.content_=content_
        self.Cc_=None
    def getFrom_(self):
        """Get email send address args None."""
        return self.from_
    def setFrom_(self,from_):
        self.from_=from_
    def getTo_(self):
        return self.to_
    def getSub_(self):
        return self.sub_
    def setSub_(self,sub_):
        self.sub_=sub_
    def getContent(self):
        return self.content_
    def setContent(self,content_):
        self.content_=content_
    def setCc_(self,Cc_):
        self.Cc_=Cc_
    def getCc_(self):
        return self.Cc_
    def setTo_(self,to_):
        self.to_=to_

class SendMail(object):
    def init(self):
        u"""
            老版本的__init__
        """
        config = ConfigParser.ConfigParser()
        caller_file = inspect.stack()[0][1]
        self.file_path=os.path.abspath(os.path.dirname(caller_file))
        try:
            config.readfp(open(self.file_path+'/conf/conf.ini'))
            comp=re.compile('(\w+)@(\w+).com')
            self.mailaddress=config.get('client','address')
            re_=re.match(comp,self.mailaddress)
            smtp_address= config.get('server',re_.group(2))
            password=config.get('client','password')
            self.s=smtp(smtp_address)
            print self.s.ehlo()[0]
            if self.s.has_extn('auth'):
                print "[INFO] start login mail server..."
                self.s.esmtp_features["auth"]="LOGIN"
                self.s.login(re_.group(1),password)
        except Exception,e:
            print '[ERROR] connection server or login error.'
            raise Exception(e)
            #sys.exit(1)        
    def __init__(self):
        u"""
        获取客户邮箱列表
        """
        self.config = ConfigParser.ConfigParser()
        self.password=self.config.get('client','password')
        caller_file = inspect.stack()[0][1]
        self.file_path=os.path.abspath(os.path.dirname(caller_file))
        try:
            self.config.readfp(open(self.file_path+'/conf/conf.ini'))
        except Exception, e:
            raise e
        clientpath=self.file_path+'/conf/client.txt'
        self.clients=[]
        with open(clientpath) as f:
            for line in f:
               self.clients.append(line)
    def login(self,mail,i):
        u"""
          登录smtp服务器, i 使用哪一个邮箱进行登录
        """
        j=i%100
        clinet=self.clients[j]
        mail.setFrom_(clinet)
        comp=re.compile('(\w+)@(\w+).com')
        re_=re.match(comp,clinet)
        smtp_address= self.config.get('server',re_.group(2))
        if self.s != None:
            self.s.quit()
        self.s=smtp(smtp_address)
        print self.s.ehlo()[0]
        if self.s.has_extn('auth'):
            print "[INFO] start login mail server..."
            self.s.esmtp_features["auth"]="LOGIN"
            self.s.login(re_.group(1),self.password)

    def send(self,mail,i):
        if i%2==0:
            self.login(i)
        msg = MIMEText(mail.getContent(),_subtype='html',_charset='utf-8')
        msg['From'] = mail.getFrom_()
        msg['To'] = mail.getTo_()
        msg['Subject'] = mail.getSub_()
        if mail.getCc_() != None:
            msg['Cc'] = mail.getCc_()
        #txt = MIMEText("mail test")
        #msg.attach(txt)
        try:
            self.s.sendmail(mail.getFrom_(),mail.getTo_(),msg.as_string())
        except Exception,e:
            print "[ERROR] send mail error,",e
        print '[INFO] send mail success.'

    def sendAll(self,mail):
        sendfilepath=self.file_path+'/conf/sendmail.txt'
        sub=None
        template=''
        i=0
        with open(sendfilepath) as f:
            for line in f:
                line=line.replace(' ','').replace('\r','').replace('\n','')
                rank=line.split(',')
                if len(rank)<3:
                    print '[ERROR] A line must have three columns:[mailaddress,subject,contextTemplate]'
                    continue
                if cmp(rank[1],'...')!=0:
                    sub=rank[1]
                if cmp(rank[2],'...')!=0:
                    file=open(rank[2])
                    try:
                        while True:
                            li=file.readline()
                            if not li:
                                break
                            template+=li
                    finally:
                        file.close()
                mail.setSub_(sub)
                mail.setContent(template)
                mail.setTo_(rank[0])
                self.send(mail)
                i+=1

    def close(self):
        self.s.quit()
        #sys.exit(0)
if __name__ == '__main__':
    mail=mail()
    try:
        sm=SendMail()
        sm.sendAll(mail)
        sm.close()
    except Exception,e:
        print e
    raw_input('Press any key to exit!')
